<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>二叉树</title>
	</head>
	<body>
		<script>
			function BinaryTree(){
				let Node = function(key){
					this.key = key;
					this.left = null;
					this.right = null;
				}
				let root = null;
				let insertNode = function(node,newNode){
					if(newNode.key < node.key){
						if(node.left === null){
							node.left = newNode;
						}else{
							insertNode(node.left,newNode);
						}
					}else{
						if(node.right === null){
							node.right = newNode;
						}else{
							insertNode(node.right,newNode);
						}
					}
				}
				this.insert = function(key){
					let newNode = new Node(key);
					if(root === null){
						root = newNode;
					} else {
						insertNode(root,newNode);
					}
				};
				//中序遍历
				let inOrderTraverseNode = function(node,callback){
					if(node !== null){
						inOrderTraverseNode(node.left,callback);
						callback(node.key);
						inOrderTraverseNode(node.right,callback);
					}
				}
				this.inOrderTraverse = function(callback){
					inOrderTraverseNode(root,callback);
				}
			}
			let nodes = [8,3,10,1,6,14,4,7,13];
			let binaryTree = new BinaryTree();
			nodes.forEach(function(key){
				binaryTree.insert(key);
			})
			let callback = function(key){
				console.log(key);
			}
			binaryTree.inOrderTraverse(callback);
		</script>
	</body>
</html>
